<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background-color:red;
    }
  </style>
</head>
<body>
  <div id="app">

    <router-link tag="button" to="/home">
      首页
    </router-link>
    <router-link tag="button"  to="/news">
      新闻页
    </router-link>
    <router-link tag="button" to="/about">
      关于我们
    </router-link>
    <hr>
    <router-view/> 
    <!-- 路由组件的出口 -->
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>

   const Home = {
     template: `
      <div>
        home页  
      </div>
     `
   }
   const About = {
     template: `
      <div>
        关于我们  
      </div>
     `
   }
   const News = {
     template: `
      <div>
        新闻页  
      </div>
     `,
     mounted(){
       console.log(this)
      
     }
   }
  
   const Login = {
     template: `
      <div>
        登录页
        <button @click="login">登录</button>  
      </div>
     `,
     methods: {
      login(){
        setTimeout(()=>{
          const token = "fheifcn489375rfxe3";
          localStorage.setItem('access_token', token)
          if(this.$route.params.from){
            // 没有登录重定向过来的
            this.$router.push(this.$route.params.from)
          }else{
            this.$router.push('/home')
          }
        },1000)
      }
     },
     mounted(){
       console.log(this)
      
     }
   }
  const routes = [ // 配置路由规则
      {
        path:'/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        component: News
      },
      {
        path: '/about',
        component: About
      },
      {
        path: '/login',
        name:'login',
        component: Login
      }
    ]
  //  定义路由
  const router = new VueRouter({
    routes
  })
  router.beforeEach((to,from,next)=>{
    /* 
    先判断 是否去登录或者注册页 这俩直接放行
    判断 用户  是否登录 
    登录了 next() 方法
    未登录 重定向到登录页
    */
   if(to.fullPath === '/login' || to.fullPath === '/register'){
     next()
   }else{
    const token = localStorage.getItem('access_token')
    if(token){
      //  登录了
      next()
    }else{
      // 没有登录
      next({
        name: 'login',
        params:{
          from: to.fullPath
        }
      });
    }
   }
  
  })
    const vm = new Vue({
      el: '#app',
      router
    })

  </script>
</body>
</html>